package com.xindaoapp.happypet.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.BaseEntity;
import com.xindaoapp.happypet.bean.Fans;
import com.xindaoapp.happypet.bean.Fans.Fan;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.utils.BitmapUtil;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.ProgressHUD;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

public class FansActivity extends UMBaseActivity implements OnClickListener {
    @ViewInject(R.id.tittle_common_cancel)
    private ImageView tittle_common_cancel;
    @ViewInject(R.id.tittle_common_content)
    private TextView tittle_common_content;

    @ViewInject(R.id.list)
    private PullToRefreshListView list;
    @ViewInject(R.id.loading)
    private FrameLayout loading;
    @ViewInject(R.id.noresult)
    private RelativeLayout noresult;
    private int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menuattention);
        ViewUtils.inject(this);
        setClick();
        initFans(page);
    }

    private void setClick() {
        tittle_common_content.setText("粉丝");
        tittle_common_cancel.setOnClickListener(this);
        list.setPullRefreshEnabled(true);
        list.setScrollLoadEnabled(true);
        list.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                fans.clear();
                page = 1;
                initFans(page);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                initFans(page);
            }
        });
        list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Intent intent = new Intent(FansActivity.this, OtherActivity.class);
                // intent.putExtra("uid", fans.get(position).uid);
                // intent.putExtra("name", fans.get(position).username);
                // intent.putExtra("face", fans.get(position).userface);
                // startActivity(intent);

                Intent intent = new Intent(FansActivity.this, MainActivity.class);
                intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                        UserInfoFragment.class.getCanonicalName());
                Bundle bundle = new Bundle();
                bundle.putString(Constants.KEY_UID, fans.get(position).uid);
                bundle.putString(Constants.KEY_USERNAME, fans.get(position).username);
                bundle.putString(Constants.KEY_USERFACE, fans.get(position).userface);
                intent.putExtra(Constants.KEY_BUNDLE, bundle);
                FansActivity.this.startActivity(intent);

            }
        });
    }

    private final List<Fan> fans = new ArrayList<Fan>();
    private Adapter adapter;

    private void initFans(int page2) {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(page2));
        params.put("uid", UserState.getUserUid());
        params.put("pagesize", "15");
        final ProgressHUD ProgressDialog =
                ProgressHUD.show(FansActivity.this, "正在加载...", true, true, null);
        AddClient.get(Address.FANS, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    if (loading.getVisibility() == View.VISIBLE) {
                        loading.setVisibility(View.GONE);
                    }
                    Fans parse = JSON.parseObject(content, Fans.class);
                    if (parse.getResult().equals("0")) {
                        if (Integer.parseInt(parse.getTotal()) == 0) {
                            noresult.setVisibility(View.VISIBLE);
                            list.setVisibility(View.GONE);
                        } else {
                            List<Fan> array = parse.array;
                            if (array.size() > 0) {
                                fans.addAll(array);
                            }
                            if (adapter == null) {
                                adapter = new Adapter(fans);
                                list.getRefreshableView().setAdapter(adapter);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                            if (Integer.parseInt(parse.getTotal()) < 10) {
                                list.setPullRefreshEnabled(false);
                                list.setScrollLoadEnabled(false);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFinish() {
                if (null != ProgressDialog && ProgressDialog.isShowing()) {
                    ProgressDialog.dismiss();
                }
                super.onFinish();
            }

            @Override
            public void onFailure(Throwable error, String content) {
                // TODO Auto-generated method stub
                super.onFailure(error, content);
            }
        });
    }

    private class Adapter extends BaseAdapter {
        private final List<Fan> fan;

        public Adapter(List<Fan> fan) {
            super();
            this.fan = fan;
        }

        @Override
        public int getCount() {
            return fan.size();
        }

        @Override
        public Object getItem(int position) {
            return fan.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(getApplicationContext(), R.layout.fans_list_item, null);
                holder.face = (CircleImageView) convertView.findViewById(R.id.face);
                holder.iv_guanzhu = (ImageView) convertView.findViewById(R.id.iv_guanzhu);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            ImageLoader.getInstance().displayImage(fan.get(position).userface, holder.face,
                    BitmapUtil.getPersonLoading());
            holder.name.setText(fan.get(position).username);
            if (fan.get(position).mutual.equals("0")) {
                holder.iv_guanzhu.setImageResource(R.drawable.other_guanzhu);
                holder.iv_guanzhu.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        RequestParams params = new RequestParams();
                        params.put("follow_uid", fan.get(position).uid);
                        params.put("follow_username", fan.get(position).username);
                        final ProgressHUD ProgressDialog =
                                ProgressHUD.show(FansActivity.this, "正在加载...", true, true, null);
                        AddClient.get(Address.GUANZHUOTHER, params, new AsyncHttpResponseHandler() {
                            @Override
                            public void onSuccess(int statusCode, String content) {
                                if (null != ProgressDialog && ProgressDialog.isShowing()) {
                                    ProgressDialog.dismiss();
                                }
                                try {
                                    BaseEntity parse = JSON.parseObject(content, BaseEntity.class);
                                    if (parse.getResult().equals("0")) {
                                        fans.get(position).mutual = "1";
                                        adapter.notifyDataSetChanged();
                                        Toast.makeText(getApplicationContext(), "关注成功",
                                                Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(getApplicationContext(), "关注失败",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                } catch (Exception e) {
                                    adapter.notifyDataSetChanged();
                                    Toast.makeText(getApplicationContext(), "已关注",
                                            Toast.LENGTH_SHORT).show();
                                }
                                super.onSuccess(statusCode, content);
                            }

                            @Override
                            public void onFailure(Throwable error, String content) {
                                if (null != ProgressDialog && ProgressDialog.isShowing()) {
                                    ProgressDialog.dismiss();
                                }
                                super.onFailure(error, content);
                            }
                        });
                    }
                });
            } else if (fan.get(position).mutual.equals("1")) {
                holder.iv_guanzhu.setImageResource(R.drawable.a_b);
                holder.iv_guanzhu.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        RequestParams params = new RequestParams();
                        params.put("follow_uid", fan.get(position).uid);
                        final ProgressHUD ProgressDialog =
                                ProgressHUD.show(FansActivity.this, "正在加载...", true, true, null);
                        AddClient.get(Address.GUZNZHUDELETE, params,
                                new AsyncHttpResponseHandler() {
                                    @Override
                                    public void onSuccess(int statusCode, String content) {
                                        if (null != ProgressDialog && ProgressDialog.isShowing()) {
                                            ProgressDialog.dismiss();
                                        }
                                        try {
                                            fans.get(position).mutual = "0";
                                            adapter.notifyDataSetChanged();
                                            holder.iv_guanzhu
                                                    .setImageResource(R.drawable.other_guanzhu);
                                            Toast.makeText(getApplicationContext(), "取消关注成功",
                                                    Toast.LENGTH_SHORT).show();
                                            super.onSuccess(statusCode, content);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFailure(Throwable error, String content) {
                                        if (null != ProgressDialog && ProgressDialog.isShowing()) {
                                            ProgressDialog.dismiss();
                                        }
                                        Toast.makeText(getApplicationContext(), "关注失败",
                                                Toast.LENGTH_SHORT).show();
                                        super.onFailure(error, content);
                                    }
                                });

                    }
                });
            }
            return convertView;
        }

    }

    class ViewHolder {
        CircleImageView face;
        ImageView iv_guanzhu;
        TextView name;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_common_cancel:
                finish();
                break;
            default:
                break;
        }
    }

}
